/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package main;

/**
 *
 * @author mx109
 */
import java.io.*;
import java.net.*;
import java.security.KeyPair;
import java.util.Calendar;
import javax.crypto.SecretKey;
import security.*;
import others.*;
import database.*;
import java.util.ArrayList;

 
public class MyServer {

  public static volatile boolean gniazdaTab[] = new boolean[100];
  static KeyPair keypair;
  static SecretKey securekey;
  ServerSocket serversocket = null;
  Socket socket = null;
  int startPort=8180;
  static ArrayList<User> L;
    
  public static void main(String[] args) throws Exception{
    keypair = AsymmetricCipher.getKeys();
    securekey = SymmetricCipher.getKey();
    System.out.println("klucz: "+keypair.getPublic());
    L = (ArrayList<User>) Serializator.loadObject("database");
  //  String s = "J2EE Security for Servlets, EJBs and Web Services asd";
    MyServer simpleserver = new MyServer();
    simpleserver.init();
  }
 
  public void init() throws Exception{
    for (int i=0; i<gniazdaTab.length; i++) gniazdaTab[i]=false;
   
      serversocket = new ServerSocket(startPort);
      System.out.println("Serwer wystartował na porcie "+startPort);
 while(true){
      socket = serversocket.accept();
 
      InputStreamReader inputstreamreader = new InputStreamReader(socket.getInputStream());
      BufferedReader bufferedreader = new BufferedReader(inputstreamreader);
    
      PrintWriter printwriter = new PrintWriter(socket.getOutputStream(),true);
 
      String datetimestring = (Calendar.getInstance()).getTime().toString();
      System.out.println("Połączono z nowym klientem");
      synchronized(gniazdaTab){
      int i=0;
      
      while(gniazdaTab[i]==true) i++;
      gniazdaTab[i]=true;
      int newport=startPort+i+1;
      Thread thread1 = new Thread(new OwnServer(newport), "thread1");
      thread1.start();
      
      printwriter.println(""+newport);
      String pk = Serializator.serializ(keypair.getPublic());
      
      printwriter.println(pk);
      System.out.println("Przekazałem port: "+newport+" i wysłałem klucz publiczny");
      }
      
      //System.out.println("Zamykam połączenie.");
      bufferedreader.close();
      inputstreamreader.close();
      printwriter.close();
      socket.close();
        }
      
     
       // socket.close();
        //serversocket.close();
      
      }
    
  }

 